<!-- 工具管理   刮刀检验 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button size="small" type="text" @click="rowUpdate(row)">维 保</el-button>
      </template>
    </avue-crud>
    <!-- 新增 详情-->
    <el-dialog v-dragDirectives ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <div class="sail-header-dialog-content">
        <avue-form ref="basicInfo" v-if="showDialog" v-model="form" :option="dialogOption">
          <template slot="PICTURE">
            <div v-if="dialogTitle != '详情' && form.PICTURE">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="picture"
                accept="image/png, image/jpeg, image/jpg"
                :on-change="changeFile"
                :headers="headersObj"
                :on-preview="handlePreview"
                :before-upload="pictureUploadBefore"
                :on-success="pictureUploadSuccess"
                :file-list="pictureList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>
              </el-upload>
            </div>
          </template>
          <template slot="INSPECTION">
            <div v-if="dialogTitle != '详情' && form.INSPECTION">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="text"
                accept=".doc,.docx,.pdf"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="textUploadBefore"
                :on-success="inspectionUploadSuccess"
                :file-list="inspectionList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
              </el-upload>
            </div>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import { getList, update } from '@/api/product/inspectSteelMesh';
import { getAreaTree, getAreaTreeByInventoryId } from '@/api/admin/storage';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import steelMeshMixin from './mixins/steelMeshMixin';
import { number } from 'echarts/core';
import { getUserInfo } from '@/api/system/user';
export default {
  name: 'EquipmentManageEquipment',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  data() {
    return {
      pageCode: 'STELL_MESH_MANAGE',
      transferDialog: false,
      form: {
        equipmentAttachmentList: []
      },
      defaults: {},
      query: {},
      loading: true,
      leftLoading: true,
      tabsIndex: '1',
      detailDialog: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      leftPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      leftForm: {},
      rightForm: {},
      leftSelectionList: [],
      rightSelectionList: [],
      leftData: [],
      rightData: [],
      selectionList: [],
      dialogTitle: '新增',
      showDialog: false,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      pictureList: [],
      inspectionList: [],
      certList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        menuWidth: 100, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称'
              }
            ]
          },
          {
            label: '规格',
            prop: 'specification',
            rules: [
              {
                required: true,
                message: '请输入规格'
              }
            ]
          },
          {
            label: '报检时间',
            prop: 'sendExamineDate'
          },

          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '待使用',
                value: 1
              },
              {
                label: '待维保',
                value: 2
              },
              {
                label: '待上线',
                value: 3
              },
              {
                label: '已上线',
                value: 4
              },
              {
                label: '不合格',
                value: 5
              },
              {
                label: '已禁用',
                value: 6
              },
              {
                label: '报废',
                value: 7
              }
            ]
            // dicUrl: '/api/blade-system/dict/dictionary?code=mes_equipment_tool_status',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // }
          },
          {
            label: '最大使用次数',
            prop: 'maxUsage'
          },
          {
            label: '已使用次数',
            prop: 'timesUsed'
          },
          {
            label: '剩余可用次数',
            prop: 'quantityAvailable',
            formatter: (val, value, label) => {
              if (!val.maxUsage || val.maxUsage == null) {
                return 0;
              } else {
                return val.maxUsage - val.timesUsed;
              }
            }
          }
        ]
      },
      dialogOption: {
        emptyBtn: false,
        submitBtn: false,
        detail: false,
        labelWidth: 160,
        group: [
          {
            label: '基本数据',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 160,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '编码',
                prop: 'equipmentCode',
                search: true,
                disabled: true,
                span: 12
              },
              {
                label: '名称',
                prop: 'equipmentName',
                disabled: true,
                search: true,
                span: 12
              },
              {
                label: '规格',
                prop: 'specification',
                disabled: true,
                span: 12
              },
              {
                label: '上次维保时间',
                prop: 'slantAngle',
                disabled: true,
                span: 12
              }
            ]
          },
          {
            label: '检验结果',
            arrow: false,
            prop: 'attachInfo',
            labelWidth: 160,
            display: true,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '检验结果',
                prop: 'examineResult',
                type: 'radio',
                span: 24,
                row: true,
                rules: [
                  {
                    required: true,
                    trigger: 'blur'
                  }
                ],
                dicData: [
                  {
                    label: '合格',
                    value: 'OK'
                  },
                  {
                    label: '不合格',
                    value: 'NG'
                  }
                ]
              },
              {
                label: '是否清空已使用次数',
                prop: 'isClearUsedTimes',
                type: 'radio',
                span: 24,
                row: true,
                // rules: [
                //   {
                //     required: true,
                //     trigger: 'blur'
                //   }
                // ],
                dicData: [
                  {
                    label: '是',
                    value: true
                  },
                  {
                    label: '否',
                    value: false
                  }
                ]
              },
              {
                label: '检验图片',
                prop: 'PICTURE',
                type: 'upload',
                span: 12
              },
              {
                label: '检验附件',
                prop: 'INSPECTION',
                type: 'upload',
                span: 12
              },
              //   {
              //     label: '投产验证附件',
              //     prop: 'CERT',
              //     type: 'upload',
              //     span: 8
              //   }
              {
                label: '检验人',
                prop: 'principalName',
                type: 'search',
                span: 12,
                appendClick: () => {
                  this.openUserCommonModal();
                }
              },
              {
                label: '备注',
                prop: 'remark',
                span: 24,
                type: 'textarea',
                maxRows: 3,
                minRows: 3,
                row: true
              }
            ]
          }
        ]
      }
    };
  },
  created() {
    this.handleWitch();
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    //   permissionList() {
    //     return {
    //       addBtn: this.vaildData(this.permission.steelMeshManage_add, false),
    //       viewBtn: this.vaildData(this.permission.steelMeshManage_view, false),
    //       delBtn: this.vaildData(this.permission.steelMeshManage_delete, false),
    //       editBtn: this.vaildData(this.permission.steelMeshManage_edit, false)
    //     };
    //   },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  methods: {
    handleWitch() {
      getUserInfo().then((res) => {
        console.log(res, 'res');
        const user = res.data.data;
        this.form = {
          principal: user.printerId,
          principalName: user.realName
        };
      });
    },
    /**
     * 打开用户选择模态框
     */
    openUserCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择负责人员（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },

    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.descs = 'send_examine_date';
      params.equipmentType = 'TOOL';
      params.subType = 'FEEDER';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalModal':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'realName', '');
          break;
        case 'areaModal':
          this.form.areaName = this._get(rowData, 'name', '');
          this.form.areaId = this._get(rowData, 'id', '');
          break;
        case 'vendorModal':
          this.form.partnerId = this._get(rowData, 'id', '');
          this.form.supplierName = this._get(rowData, 'name', '');
          break;
      }
    },
    pictureUploadSuccess(res) {
      if (!this.form.equipmentAttachmentList) {
        this.form.equipmentAttachmentList = [];
      }
      this.form.PICTURE = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'PICTURE'
      });
    },
    inspectionUploadSuccess(res) {
      if (!this.form.equipmentAttachmentList) {
        this.form.equipmentAttachmentList = [];
      }
      this.form.INSPECTION = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'INSPECTION'
      });
    },

    changeFile(files, fileList) {
      // if (fileList.length > 1) {
      //   fileList.splice(0, 1);
      // }
    },
    /**
     * 上传前方法
     */
    pictureUploadBefore(file) {
      console.log(file);
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        return false;
      }
    },
    textUploadBefore(file) {
      if (file.name.split('.')[1] != 'doc' && file.name.split('.')[1] != 'docx' && file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传dox/docx/pdf文件！'
        });
        return false;
      }
    },

    /**
     * 提交
     */
    async submit() {
      if (!this.form.examineResult) {
        this.$message.warning('请选择检验结果');
        return;
      }
      let prm = {
        examineByName: this.form.principalName,
        examineBy: this.form.principal,
        remark: this.form.remark,
        examineResult: this.form.examineResult,
        isClearUsedTimes: this.form.isClearUsedTimes,
        equipmentId: this.form.id,
        attachmentList: this.form.equipmentAttachmentList
      };

      update(prm).then((res) => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: res.data.msg
        });
        this.showDialog = false;
      });
    },

    rowUpdate(row) {
      this.showDialog = true;
      this.dialogOption.detail = false;
      this.dialogTitle = '维 保';
      this.form.tensionWarn = row.tensionWarn;
      this.form.areaName = row.areaName;
      this.form.specification = row.specification;
      this.form.slantAngle = row.latestMaintain;
      this.form.equipmentName = row.name;
      this.form.equipmentCode = row.code;
      this.form.examineResult = row.result;
      this.form.id = row.id;
      this.handleWitch();
    },

    closeDialog() {
      this.form = {};
      this.pictureList = [];
      this.inspectionList = [];
      this.certList = [];
    },

    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.tranfer-dialog {
  ::v-deep .avue-crud__search {
    width: 100% !important;
    border: none !important;
  }
  ::v-deep .avue-crud__right {
    display: none !important;
  }
}
</style>
